// ignore: file_names
// ignore_for_file: file_names

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/**
 * 自定义组件，用来加载原生view
 */

class TestView extends StatefulWidget {
  double width;

  TestView({Key? key, this.width = 300}) : super(key: key);

  @override
  _TestViewState createState() => _TestViewState();
}

class _TestViewState extends State<TestView> {
  late MethodChannel _channel;
  late EventChannel _eventChannel;
  int viewId = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: 40 + 100.0,
      color: Colors.red,
      child: Column(
        children: [
          GestureDetector(
            onTap: () {
              _channel.invokeMethod("updateText", {"updateText": "更改了"});
            },
            child: Container(
              height: 40,
              color: Colors.white,
              child: Text("点我更新原生文字"),
            ),
          ),
          Expanded(
            child: Platform.isIOS
                ? UiKitView(
                    viewType: "YcPluginLearnPlugin.testView",
                    creationParams: {"content": "flutter 传入的文本内容，在原生页面上展示"},
                    creationParamsCodec: StandardMessageCodec(),
                    onPlatformViewCreated: (id) {
                      print("初始化完成");
                      viewId = id;
                      _channel = MethodChannel('yc_plugin_learn_view_$viewId');
                      _eventChannel = EventChannel(
                          "yc_plugin_learn_eventChannel_view_$viewId");
                      _eventChannel.receiveBroadcastStream().listen((data) {
                        String type = data["type"];
                        print("收到原生 主动发送的消息 $data");
                      });
                    },
                  )
                : AndroidView(
                    viewType: "YcPluginLearnPlugin.testView",
                    creationParams: {"content": "flutter 传入的文本内容，在原生页面上展示"},
                    creationParamsCodec: StandardMessageCodec(),
                    onPlatformViewCreated: (id) {
                      print("初始化完成");
                      viewId = id;
                      _channel = MethodChannel('yc_plugin_learn_view_$viewId');
                      _eventChannel = EventChannel(
                          "yc_plugin_learn_eventChannel_view_$viewId");
                      _eventChannel.receiveBroadcastStream().listen((data) {
                        String type = data["type"];
                        print("收到原生 主动发送的消息 $data");
                      });
                    },
                  ),
          ),
        ],
      ),
    );
  }
}
